﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Rotempco.ORM.Generator.Objects;
using Microsoft.Win32;
using System.IO;
using Rotempco.ORM.Generator.Logic;

namespace Rotempco.ORM.Generator
{
    /// <summary>
    /// Interaction logic for EnumEditor.xaml
    /// </summary>
    public partial class EnumEditor : Window
    {
        private string _TableName;
        private DatabaseColumn _DatabaseColumn;
        private RotempcoSettings _ProjectSettings;

        public string EnumName { get; private set; }
        public string EnumNamespace { get; set; }

        public EnumEditor()
        {
            InitializeComponent();
        }

        public void SetSettings(RotempcoSettings rotempcoSettings, string tableName, DatabaseColumn databaseColumn)
        {
            _ProjectSettings = rotempcoSettings;
            _TableName = tableName;
            _DatabaseColumn = databaseColumn;

            textBlock_EnumName.Text = databaseColumn.Name;
            textBlock_ElementName.Focus();

            label_TableName.Content += tableName;
            label_ColumnsName.Content += databaseColumn.Name;
        }

        private void button_Browse_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Enum files|*.cs";
            if (openFileDialog.ShowDialog() == true)
            {
                textbox_ExistingEnumPath.Text = openFileDialog.FileName;

                LoadEnum(textbox_ExistingEnumPath.Text);
                Close();
            }
        }

        private void LoadEnum(string enumPath)
        {
            string enumContent = File.ReadAllText(enumPath);

            int afterNamespaceStart = enumContent.IndexOf("namespace ") + 10;
            int namespaceEnum = enumContent.IndexOf(Environment.NewLine, afterNamespaceStart);

            string enumNameSpace = enumContent.Substring(afterNamespaceStart, namespaceEnum - afterNamespaceStart);

            int afterEnumStart = enumContent.IndexOf(" enum ") + 6;
            int enumNameStart = enumContent.IndexOf(Environment.NewLine, afterEnumStart);

            string enumName = enumContent.Substring(afterEnumStart, enumNameStart - afterEnumStart);

            string enumIdentifier = _TableName + "_" + _DatabaseColumn.Name;

            string projectNamespace = _ProjectSettings.SettingsFile.Substring(0, _ProjectSettings.SettingsFile.LastIndexOf('\\'));

            string enumSavePath_ForProjectsFile = enumPath.Substring(projectNamespace.Length + 1);

            EnumName = enumName;
            EnumNamespace = enumNameSpace;

            _ProjectSettings.SetKey("@EnumDefinitions_" + enumIdentifier, enumName);
            _ProjectSettings.SetKey("@EnumDefinitions_Path_" + enumIdentifier, enumSavePath_ForProjectsFile);
            _ProjectSettings.SetKey("@EnumDefinitions_Namespace_" + enumIdentifier, enumNameSpace);

            string projectNamespaceProject = FileNameLogic.GetProjectNamespace(_ProjectSettings);

            string enumSavePath_ForProjectsFileProjectFile = enumSavePath_ForProjectsFile.Replace( projectNamespaceProject + "\\", "");

            ProjectFileLogic.InsertAndSaveElementToProject(_ProjectSettings, new FileInfo(_ProjectSettings.SettingsFile).Directory.FullName, enumSavePath_ForProjectsFileProjectFile);
        }

        private void textBlock_ElementName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
                AddEnumElement();
        }

        private void textBlock_ElementId_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
                AddEnumElement();
        }

        private void AddEnumElement()
        {
            try
            {
                string enumElementName = "";
                int? enumId = null;

                if (textBlock_ElementName.Text.Contains('='))
                {
                    string[] enumBlocks = textBlock_ElementName.Text.Split('=');
                    enumElementName = enumBlocks[0].Trim();
                    enumId = int.Parse(enumBlocks[1].Trim());
                }
                else
                {
                    enumElementName = textBlock_ElementName.Text.Trim();

                    if (!string.IsNullOrWhiteSpace(textBlock_ElementId.Text))
                    {
                        enumId = int.Parse(textBlock_ElementId.Text);

                        textBlock_ElementId.Text = (enumId + 1).Value.ToString();
                    }
                }

                listBox1.Items.Add(new KeyValuePair<string, int?>(enumElementName, enumId));
                textBlock_ElementName.Text = "";
            }
            catch (Exception exception)
            {
                MessageBox.Show("Error: " + exception);
            }
        }

        private void button_Remove_Click(object sender, RoutedEventArgs e)
        {
            listBox1.SelectedItems.Cast<KeyValuePair<string, int?>>().ToList().ForEach(a => listBox1.Items.Remove(a));
        }

        private void button_Generate_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(textBlock_EnumName.Text))
            {
                MessageBox.Show("Please fillout EnumName");
                return;
            }

            SaveFileDialog saveFileDialog = new SaveFileDialog();

            string enumName = textBlock_EnumName.Text;

            saveFileDialog.FileName = enumName + ".cs";

            if (saveFileDialog.ShowDialog() == false)
                return;

            string enumPath = saveFileDialog.FileName;

            string projectNamespace = _ProjectSettings.SettingsFile.ToLower().Substring(0, _ProjectSettings.SettingsFile.LastIndexOf('\\'));

            string enumSavePath_ForProjectsFile = new FileInfo(enumPath).Directory.FullName.Substring(projectNamespace.Length + 1);

            string enumNamespace = enumSavePath_ForProjectsFile.Replace('\\', '.');

            string enumTemplateContent = TemplateFiller.FillEnumTemplate(enumNamespace, enumName, listBox1.Items.Cast<KeyValuePair<string, int?>>().ToList());

            File.WriteAllText(enumPath, enumTemplateContent);

            LoadEnum(enumPath);
            Close();
            //            ProjectFileLogic.InsertAndSaveElementToProject(_ProjectSettings, _ProjectSettings.SettingsFile, enumPath);
        }
    }
}
